# app/user/services/cruds.py
import traceback

from fastapi import Depends, HTTPException, status

from app.core.handlers.database import SessionDep
from app.core.handlers.loggers import logger
from app.core.handlers.response import SuccessResponse
from app.user.cruds import RoleCRUD, UserCRUD
from app.user.models.role import RoleCreate
from app.user.models.user import UserCreate


class UserService:
    """用户服务层"""

    def __init__(self, db: SessionDep, user_curd: UserCRUD = Depends()):
        self.db = db
        self.user_curd = user_curd

    async def get_user(self, user_id: int):
        """获取用户详情"""
        user = await self.user_curd.get_user(user_id)
        if user:
            return SuccessResponse(data=user.model_dump(), message="用户查询成功")
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    async def get_users(self, user_ids: str):
        """批量获取用户详情"""
        users = await self.user_curd.get_users(user_ids)
        if users:
            return SuccessResponse(
                data=[user.to_dict() for user in users], message="用户查询成功"
            )
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="所有用户不存在"
        )

    async def create_user(self, user_data: UserCreate):
        try:
            # 检查用户名是否已存在
            if await self.user_curd.get_user_by_username(user_data.username):
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST, detail="用户已存在"
                )

            new_user = await self.user_curd.create_user(user_data)
            self.db.commit()
            self.db.refresh(new_user)
            return SuccessResponse(
                data=new_user.model_dump(), message="用户创建成功", code=201
            )

        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"用户创建失败: {str(e)}",
            )


# 修改后的 app/user/services/cruds.py


class RoleService:
    """角色服务层"""

    def __init__(
        self,
        db: SessionDep,
        user_crud: UserCRUD = Depends(),
        role_crud: RoleCRUD = Depends(),
    ):
        self.db = db
        self.user_crud = user_crud
        self.role_crud = role_crud

    async def get_role(self, role_id: int):
        """获取角色详情"""
        role = await self.role_crud.get_role(role_id)
        if role:
            return SuccessResponse(data=role.model_dump(), message="角色查询成功")
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")

    async def create_role(
        self,
        role_data: RoleCreate,
    ):
        """创建新角色"""
        try:
            # 使用 CRUD 层的方法检查角色是否已存在
            if self.role_crud.get_role_by_name(role_data.name):
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST, detail="角色已存在"
                )

            # 创建新角色
            new_role = await self.role_crud.create_role(role_data)
            self.db.commit()
            self.db.refresh(new_role)
            return SuccessResponse(
                data=new_role.to_dict(), message="角色创建成功", code=201
            )

        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"创建角色失败: {str(e)}",
            )

    async def link_role_to_user(self, user_id: int, role_ids: str):
        """
        批量关联多个角色到用户
        :param user_id: 用户ID
        :param role_ids: 角色ID字符串，用逗号分隔，如 "1,2,3"
        :return: 操作结果响应
        """
        try:
            user = await self.user_crud.get_user(user_id)
            if not user:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在"
                )
            roles = await self.role_crud.get_roles(role_ids)

            # 批量关联所有角色
            for role in roles:
                user.add_role(role)

            self.db.commit()
            self.db.refresh(user)
            return SuccessResponse(message="关联成功")

        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"关联失败: {str(e)}",
            )

    async def unlink_user_role(self, user_id: int, role_ids: str):
        try:
            user = await self.user_crud.get_user(user_id)
            roles = await self.role_crud.get_roles(role_ids)

            for role in roles:
                role.revoke_from_user(user)

            self.db.commit()
            self.db.refresh(user)
            return SuccessResponse(message="解除关联成功")
        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"解除关联失败: {str(e)}",
            )
